<template>
  <view class="inbound-execute">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="cuIcon-back"></text>
        </view>
        <view class="nav-title">物料入库执行</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 入库单基本信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">入库单信息</text>
          <view class="status-badge" :class="statusClass">
            {{ getStatusText(orderInfo.status) }}
          </view>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">入库单号:</text>
            <text class="info-value">{{ orderInfo.inboundNo }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">业务类型:</text>
            <text class="info-value">{{ orderInfo.businessTypeName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">关联业务单号:</text>
            <text class="info-value">{{ orderInfo.businessNo || "-" }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">计划入库时间:</text>
            <text class="info-value">{{
              formatDate(orderInfo.planInboundTime)
            }}</text>
          </view>
        </view>
      </view>

      <!-- 入库明细信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">入库明细</text>
          <text class="detail-count">共{{ detailList.length }}项</text>
        </view>
        <view class="detail-list">
          <view
            v-for="(item, index) in detailList"
            :key="index"
            class="detail-item"
          >
            <view class="detail-header">
              <text class="material-code">{{ item.materialCode }}</text>
              <view class="material-status" :class="item.statusClass">
                {{ item.statusText }}
              </view>
            </view>
            <view class="detail-content">
              <view class="detail-row">
                <text class="detail-label">规格:</text>
                <text class="detail-value">{{
                  item.specification || "-"
                }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">颜色:</text>
                <text class="detail-value">{{ item.color || "-" }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">计划入库数量:</text>
                <text class="detail-value quantity"
                  >{{ item.planQuantity }}{{ item.unit || "" }}</text
                >
              </view>
              <view class="detail-row">
                <text class="detail-label">实际入库数量:</text>
                <text class="detail-value quantity actual"
                  >{{ getActualQuantity(item) }}{{ item.unit || "" }}</text
                >
              </view>
              <view class="detail-row">
                <text class="detail-label">计划仓库:</text>
                <text class="detail-value">{{
                  item.planWarehouseName || "-"
                }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">计划仓位:</text>
                <text class="detail-value">{{
                  item.planLocationName || "-"
                }}</text>
              </view>
            </view>

            <!-- 执行入库操作区域 -->
            <view v-if="canExecute">
              <view
                v-for="(executeArea, executeIndex) in item.executeAreas"
                :key="executeIndex"
                class="execute-section"
              >
                <view class="execute-header" v-if="executeIndex > 0">
                  <text class="execute-title"
                    >执行区域{{ executeIndex + 1 }}</text
                  >
                </view>
                <view class="input-row">
                  <text class="input-label">入库数量:</text>
                  <input
                    class="quantity-input"
                    type="number"
                    v-model="executeArea.executeQuantity"
                    :placeholder="`最大${
                      item.planQuantity - (item.actualQuantity || 0)
                    }`"
                  />
                  <text class="unit-text">{{ item.unit || "" }}</text>
                </view>
                <view class="input-row">
                  <text class="input-label">实际仓库:</text>
                  <picker
                    :value="executeArea.executeWarehouseIndex"
                    :range="warehouseList"
                    range-key="warehouseName"
                    @change="onWarehouseChange($event, index, executeIndex)"
                  >
                    <view class="picker-input">
                      <text class="picker-text">{{
                        executeArea.executeWarehouseName || "请选择仓库"
                      }}</text>
                      <text class="cuIcon-unfold picker-icon"></text>
                    </view>
                  </picker>
                </view>
                <view class="input-row">
                  <text class="input-label">实际库位:</text>
                  <picker
                    :value="executeArea.executeLocationIndex"
                    :range="
                      getLocationsByWarehouse(executeArea.executeWarehouseId)
                    "
                    range-key="displayName"
                    @change="onLocationChange($event, index, executeIndex)"
                  >
                    <view class="picker-input">
                      <text
                        class="picker-text"
                        :class="executeArea.locationStatusClass"
                        >{{
                          executeArea.executeLocationName || "请选择库位"
                        }}</text
                      >
                      <text class="cuIcon-unfold picker-icon"></text>
                    </view>
                  </picker>
                </view>
                <view class="input-row">
                  <text class="input-label">库位状态:</text>
                  <view class="status-display">
                    <text
                      class="status-text"
                      :class="executeArea.locationStatusClass"
                      >{{ executeArea.executeLocationStatus || "占用" }}</text
                    >
                  </view>
                </view>
                <view
                  class="input-row"
                  v-if="executeArea.executeLocationStatus !== '已满'"
                >
                  <view
                    class="location-full-btn"
                    @click="markLocationFull(index, executeIndex)"
                  >
                    <text class="cuIcon-add"></text>
                    <text>库位已满</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="canExecute">
      <view class="action-btn cancel" @click="goBack">取消</view>
      <view class="action-btn confirm" @click="executeInbound">执行入库</view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-mask" v-if="loading">
      <view class="loading-content">
        <text class="cuIcon-loading2 cu-spin"></text>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "InboundExecute",
  data() {
    return {
      loading: false,
      inboundOrderId: "",
      inboundNo: "",
      orderInfo: {},
      detailList: [],
      warehouseList: [],
      locationList: {},
      locationStatusOptions: [
        { value: "1", label: "空闲" },
        { value: "2", label: "占用" },
        { value: "3", label: "锁定" },
        { value: "4", label: "禁用" },
        { value: "5", label: "已满" },
      ],
    };
  },

  computed: {
    statusClass() {
      return this.calculateStatusClass(this.orderInfo.status);
    },

    canExecute() {
      return this.orderInfo.status === 1; // 待入库状态
    },
  },

  onLoad(options) {
    this.inboundOrderId = options.inboundOrderId;
    this.inboundNo = options.inboundNo;
    this.loadWarehouseList();
    this.loadOrderInfo();
    this.loadOrderDetails();
  },

  methods: {
    goBack() {
      uni.navigateBack();
    },

    async loadOrderInfo() {
      if (!this.inboundOrderId) return;

      this.loading = true;
      try {
        const response = await this.$http.get("/wms/inboundOrder/queryById", {
          params: { id: this.inboundOrderId },
        });

        if (response.data && response.data.success) {
          this.orderInfo = response.data.result || {};
        } else {
          uni.showToast({
            title: "加载入库单信息失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载入库单信息失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    async loadOrderDetails() {
      if (!this.inboundOrderId) return;

      try {
        const response = await this.$http.get(
          "/wms/inboundOrder/queryDetailListForMobile",
          {
            params: { inboundOrderId: this.inboundOrderId },
          }
        );

        if (response.data && response.data.success) {
          // 检查返回的数据结构
          let detailData = response.data.result || [];

          // 如果返回的是包含detailList的订单数据，提取detailList
          if (detailData.length > 0 && detailData[0].detailList) {
            detailData = detailData[0].detailList || [];
          }

          this.detailList = detailData.map((item) => {
            // 创建执行区域数组
            item.executeAreas = [
              {
                // 入库数量逻辑：
                // 当实际入库数量不为0时，代表该明细已经执行过，则入库数量等于实际入库数量
                // 当实际入库数量=0时，入库数量等于计划入库数量
                executeQuantity:
                  item.actualQuantity && parseFloat(item.actualQuantity) > 0
                    ? parseFloat(item.actualQuantity)
                    : item.planQuantity,
                executeWarehouseIndex: 0,
                executeWarehouseId: item.planWarehouseId,
                executeWarehouseName: item.planWarehouseName,
                executeLocationIndex: 0,
                executeLocationId: item.planLocationId,
                executeLocationName: item.planLocationName,
                executeLocationStatus: "占用",
                locationStatusClass: "location-status-occupied",
              },
            ];

            item.statusClass = this.getDetailStatusClass(item);
            item.statusText = this.getDetailStatusText(item);

            // 预加载计划仓库的库位数据
            if (item.planWarehouseId) {
              this.loadLocationsByWarehouse(item.planWarehouseId);
            }

            return item;
          });
        }
      } catch (error) {
        console.error("加载入库明细失败:", error);
        uni.showToast({
          title: "加载明细失败",
          icon: "none",
        });
      }
    },
    //执行
    async executeInbound() {
      // 构建执行数据
      const executeItems = [];
      for (const item of this.detailList) {
        // 遍历每个明细的执行区域
        for (const executeArea of item.executeAreas) {
          if (
            executeArea.executeQuantity &&
            parseFloat(executeArea.executeQuantity) > 0
          ) {
            // 验证必填字段
            if (!executeArea.executeLocationId) {
              uni.showToast({
                title: `${item.materialCode}请输入仓位`,
                icon: "none",
              });
              return;
            }

            executeItems.push({
              detailId: item.id,
              materialCode: item.materialCode,
              quantity: parseFloat(executeArea.executeQuantity),
              actualWarehouseId: executeArea.executeWarehouseId,
              actualLocationId: executeArea.executeLocationId,
              actualWarehouseName: executeArea.executeWarehouseName,
              actualLocationName: executeArea.executeLocationName,
              locationStatus: executeArea.executeLocationStatus,
            });
          }
        }
      }

      if (executeItems.length === 0) {
        uni.showToast({
          title: "请至少选择一项进行入库",
          icon: "none",
        });
        return;
      }

      // 确认执行
      uni.showModal({
        title: "确认执行",
        content: `确定要执行${executeItems.length}项物料的入库操作吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.performInbound(executeItems);
          }
        },
      });
    },

    async performInbound(executeItems) {
      this.loading = true;
      try {
        // 按明细ID分组执行项目
        const detailGroups = {};
        executeItems.forEach((item) => {
          if (!detailGroups[item.detailId]) {
            detailGroups[item.detailId] = [];
          }
          detailGroups[item.detailId].push(item);
        });

        // 转换为后端期望的格式
        const details = Object.keys(detailGroups).map((detailId) => {
          const executeGroup = detailGroups[detailId];
          const firstItem = executeGroup[0];

          // 查找对应的明细信息
          const detailInfo = this.detailList.find(
            (detail) => detail.id === detailId
          );

          // 计算总的实际入库数量
          const totalActualQuantity = executeGroup.reduce(
            (sum, item) => sum + item.quantity,
            0
          );

          // 构建完整的明细参数，与Web端保持完全一致
          const detailParams = {
            id: detailId,
            actualWarehouseId: firstItem.actualWarehouseId,
            actualLocationId: firstItem.actualLocationId,
            actualQuantity: totalActualQuantity,
            remark: detailInfo
              ? detailInfo.remark || "移动端执行入库"
              : "移动端执行入库",
            // 添加计划数量，用于后端计算入库状态
            planQuantity: detailInfo ? detailInfo.planQuantity : 0,
            // 添加物料编码，用于后端更新相同物料的其他明细
            materialCode: firstItem.materialCode,
            // 添加物料ID，用于后端更新库存
            materialId: detailInfo ? detailInfo.materialId : null,
            // 添加单位成本，用于后端更新库存成本
            unitCost: detailInfo ? detailInfo.unitCost || 0 : 0,
            // 添加标记，表示需要更新库存
            updateInventory: true,
          };

          // 当实际数量大于0且库位状态不是已满时，设置库位状态为"占用(2)"
          const isLocationFull =
            firstItem.locationStatus === "已满" ||
            firstItem.locationStatus === "5";
          if (totalActualQuantity > 0 && !isLocationFull) {
            detailParams.updateLocationStatus = true;
            detailParams.locationStatus = "2"; // 设置为"占用(2)"
          }

          // 如果有多个执行区域，添加执行区域信息
          if (executeGroup.length > 1) {
            detailParams.executeAreas = executeGroup.map((item) => ({
              warehouseId: item.actualWarehouseId,
              locationId: item.actualLocationId,
              warehouseName: item.actualWarehouseName,
              locationName: item.actualLocationName,
              quantity: item.quantity,
              locationStatus: item.locationStatus,
            }));
          }

          return detailParams;
        });

        const response = await this.$http.post(
          "/wms/inboundOrder/batchConfirmInboundWithBody",
          {
            inboundOrderId: this.inboundOrderId,
            details: details,
          }
        );

        if (response.data && response.data.success) {
          uni.showToast({
            title: "入库执行成功",
            icon: "success",
          });

          // 立即刷新数据，确保实际入库数量正确显示
          this.loadOrderInfo();
          this.loadOrderDetails();
        } else {
          uni.showToast({
            title: response.data?.message || "执行失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("执行入库失败:", error);
        let errorMessage = "执行失败";

        if (error && error.errMsg) {
          errorMessage = error.errMsg;
        } else if (error && error.data && error.data.message) {
          errorMessage = error.data.message;
        } else if (error && error.message) {
          errorMessage = error.message;
        } else if (error && error.statusText) {
          errorMessage = error.statusText;
        } else if (typeof error === "string") {
          errorMessage = error;
        }

        uni.showToast({
          title: errorMessage,
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    calculateStatusClass(status) {
      const statusMap = {
        1: "status-pending", // 待入库
        2: "status-completed", // 已入库
        3: "status-partial", // 部分入库
        4: "status-rejected", // 已驳回
      };
      return statusMap[status] || "status-default";
    },

    getDetailStatusClass(item) {
      const actualQty = item.actualQuantity || 0;
      const planQty = item.planQuantity || 0;

      if (actualQty === 0) {
        return "detail-pending";
      } else if (actualQty >= planQty) {
        return "detail-completed";
      } else {
        return "detail-partial";
      }
    },

    getDetailStatusText(item) {
      const actualQty = item.actualQuantity || 0;
      const planQty = item.planQuantity || 0;

      if (actualQty === 0) {
        return "待入库";
      } else if (actualQty >= planQty) {
        return "已完成";
      } else {
        return "部分入库";
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return "-";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")}`;
    },

    getStatusText(status) {
      const statusMap = {
        1: "待入库",
        2: "已入库",
        3: "部分入库",
        4: "已驳回",
      };
      return statusMap[status] || "未知状态";
    },

    async loadWarehouseList() {
      try {
        const response = await this.$http.get("/wms/warehouse/listAll");
        if (response.data && response.data.success) {
          this.warehouseList = response.data.result || [];
        }
      } catch (error) {
        console.error("加载仓库列表失败:", error);
      }
    },

    async loadLocationsByWarehouse(warehouseId) {
      if (!warehouseId || this.locationList[warehouseId]) return;

      try {
        const response = await this.$http.get(
          "/wms/location/listByWarehouseId",
          {
            params: { warehouseId },
          }
        );
        if (response.data && response.data.success) {
          this.$set(this.locationList, warehouseId, response.data.result || []);
        }
      } catch (error) {
        console.error("加载库位列表失败:", error);
      }
    },

    getLocationsByWarehouse(warehouseId) {
      const locations = this.locationList[warehouseId] || [];
      // 状态值对应关系
      const statusMap = {
        1: "空闲",
        2: "占用",
        3: "锁定",
        4: "禁用",
        5: "已满",
      };

      // 状态颜色映射
      const statusColorMap = {
        1: "location-status-idle", // 空闲 - 绿色
        2: "location-status-occupied", // 占用 - 橙色
        3: "location-status-locked", // 锁定 - 红色
        4: "location-status-disabled", // 禁用 - 灰色
        5: "location-status-full", // 已满 - 深橙色
      };

      // 为每个库位添加displayName属性，包含名称和状态，以及颜色标识
      return locations.map((location) => {
        const statusText = statusMap[location.status] || "空闲";
        const colorIndicator = this.getStatusColorIndicator(location.status);
        return {
          ...location,
          displayName: `${colorIndicator} ${location.locationName}(${statusText})`,
          statusClass:
            statusColorMap[location.status] || "location-status-idle",
        };
      });
    },

    async onWarehouseChange(e, itemIndex, executeIndex) {
      const warehouseIndex = e.detail.value;
      const warehouse = this.warehouseList[warehouseIndex];

      if (warehouse) {
        const executeArea =
          this.detailList[itemIndex].executeAreas[executeIndex];
        executeArea.executeWarehouseIndex = warehouseIndex;
        executeArea.executeWarehouseId = warehouse.id;
        executeArea.executeWarehouseName = warehouse.warehouseName;

        // 重置库位选择
        executeArea.executeLocationIndex = 0;
        executeArea.executeLocationId = "";
        executeArea.executeLocationName = "";

        // 加载对应仓库的库位
        await this.loadLocationsByWarehouse(warehouse.id);
      }
    },

    onLocationChange(e, itemIndex, executeIndex) {
      const locationIndex = e.detail.value;
      const executeArea = this.detailList[itemIndex].executeAreas[executeIndex];
      const locations = this.getLocationsByWarehouse(
        executeArea.executeWarehouseId
      );
      const location = locations[locationIndex];

      if (location) {
        executeArea.executeLocationIndex = locationIndex;
        executeArea.executeLocationId = location.id;
        executeArea.executeLocationName = location.displayName;
        // 同时设置库位状态
        const statusMap = {
          1: "空闲",
          2: "占用",
          3: "锁定",
          4: "禁用",
          5: "已满",
        };
        const statusColorMap = {
          1: "location-status-idle", // 空闲 - 绿色
          2: "location-status-occupied", // 占用 - 橙色
          3: "location-status-locked", // 锁定 - 红色
          4: "location-status-disabled", // 禁用 - 灰色
          5: "location-status-full", // 已满 - 深橙色
        };
        // 设置库位状态默认为占用
        executeArea.executeLocationStatus = "占用";
        executeArea.locationStatusClass = "location-status-occupied";
      }
    },

    markLocationFull(itemIndex, executeIndex) {
      const item = this.detailList[itemIndex];
      const executeArea = item.executeAreas[executeIndex];

      // 检查是否已选择库位
      if (!executeArea.executeLocationId) {
        uni.showToast({
          title: "请先选择库位",
          icon: "none",
        });
        return;
      }

      // 检查是否已输入数量
      if (
        !executeArea.executeQuantity ||
        parseFloat(executeArea.executeQuantity) <= 0
      ) {
        uni.showToast({
          title: "请先输入入库数量",
          icon: "none",
        });
        return;
      }

      // 计算当前实际入库数量和剩余数量
      const currentActualQuantity = this.getActualQuantity(item);
      const remainingQty = item.planQuantity - currentActualQuantity;

      // 显示确认对话框
      const confirmContent =
        remainingQty > 0
          ? `当前物料 ${item.materialName}(${item.materialCode}) 的计划数量为 ${item.planQuantity}，实际入库数量为 ${currentActualQuantity}，确认标记库位已满并创建新明细以容纳剩余数量 ${remainingQty} ${item.unit} 吗？`
          : `当前物料 ${item.materialName}(${item.materialCode}) 的计划数量已全部入库，确认标记库位已满吗？`;

      uni.showModal({
        title: "确认库位已满",
        content: confirmContent,
        success: (res) => {
          if (res.confirm) {
            this.processLocationFull(item, executeArea, remainingQty);
          }
        },
      });
    },

    async processLocationFull(item, executeArea, remainingQty) {
      try {
        // 仿照Web端逻辑，进行数量验证和默认值设置
        const actualQty = parseFloat(executeArea.executeQuantity || 0);
        const planQty = parseFloat(item.planQuantity || 0);

        // 当实际数量为0且库位未满时，默认使用计划数量
        if (actualQty === 0 && executeArea.executeLocationStatus !== "已满") {
          executeArea.executeQuantity = item.planQuantity;
          uni.showToast({
            title: `实际数量为0，已默认设置为计划数量：${item.planQuantity}`,
            icon: "none",
            duration: 2000,
          });
        }

        // 验证实际数量不超过计划数量
        const finalActualQty = parseFloat(executeArea.executeQuantity || 0);
        if (finalActualQty > planQty) {
          uni.showToast({
            title: "实际入库数量不能超过计划入库数量",
            icon: "none",
          });
          executeArea.executeQuantity = item.planQuantity;
          return;
        }

        // 先调用updateDetail接口更新明细状态，与Web端逻辑一致
        await this.updateDetailLocationStatus(item, executeArea, remainingQty);

        // 标记当前库位为已满 - 确保UI状态正确更新
        executeArea.executeLocationStatus = "已满";
        executeArea.locationStatusClass = "location-status-full";

        // 同步更新库位列表中的状态
        this.updateLocationStatus(
          executeArea.executeWarehouseId,
          executeArea.executeLocationId,
          5
        );

        // 强制更新Vue响应式数据，确保UI正确显示
        this.$forceUpdate();

        // 如果有剩余数量，创建新的入库明细
        if (remainingQty > 0) {
          await this.createNewDetailForRemaining(item, remainingQty);
          uni.showToast({
            title: `库位已满，已创建新明细处理剩余${remainingQty}${item.unit}`,
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "库位已满，入库完成",
            icon: "success",
          });
        }

        // 使用queryDetailListForMobile接口刷新入库明细列表，确保获取最新状态
        await this.refreshDetailList();
      } catch (error) {
        console.error("处理库位已满失败:", error);
        uni.showToast({
          title: "处理失败，请重试",
          icon: "none",
        });
      }
    },

    // 专门用于库位已满后刷新明细列表的方法
    async refreshDetailList() {
      try {
        const response = await this.$http.get(
          "/wms/inboundOrder/queryDetailListForMobile",
          {
            params: { inboundOrderId: this.inboundOrderId },
          }
        );

        if (response.data && response.data.success) {
          // 检查返回的数据结构
          let detailData = response.data.result || [];

          // 如果返回的是包含detailList的订单数据，提取detailList
          if (detailData.length > 0 && detailData[0].detailList) {
            detailData = detailData[0].detailList || [];
          }

          // 处理刷新后的明细数据，保持执行区域结构
          this.detailList = detailData.map((item) => {
            // 为每个明细创建执行区域数组
            const executeAreas = [];

            // 根据明细状态创建执行区域
            if (item.actualQuantity && parseFloat(item.actualQuantity) > 0) {
              // 明细A：已执行过的明细，显示实际入库数量
              executeAreas.push({
                executeQuantity: parseFloat(item.actualQuantity),
                executeWarehouseIndex: 0,
                executeWarehouseId: item.planWarehouseId,
                executeWarehouseName: item.planWarehouseName,
                executeLocationIndex: 0,
                executeLocationId: item.planLocationId,
                executeLocationName: item.planLocationName,
                executeLocationStatus:
                  item.locationStatus === "5" ? "已满" : "占用",
                locationStatusClass:
                  item.locationStatus === "5"
                    ? "location-status-full"
                    : "location-status-occupied",
              });
            } else {
              // 明细B：新创建的明细或未执行的明细，显示计划入库数量
              executeAreas.push({
                executeQuantity: item.planQuantity,
                executeWarehouseIndex: 0,
                executeWarehouseId: item.planWarehouseId,
                executeWarehouseName: item.planWarehouseName,
                executeLocationIndex: item.planLocationId ? 0 : -1,
                executeLocationId: item.planLocationId || "",
                executeLocationName: item.planLocationName || "",
                executeLocationStatus: "占用",
                locationStatusClass: "location-status-occupied",
              });
            }

            item.executeAreas = executeAreas;
            item.statusClass = this.getDetailStatusClass(item);
            item.statusText = this.getDetailStatusText(item);

            // 预加载计划仓库的库位数据
            if (item.planWarehouseId) {
              this.loadLocationsByWarehouse(item.planWarehouseId);
            }

            return item;
          });
        } else {
          throw new Error(response.data?.message || "获取明细数据失败");
        }
      } catch (error) {
        console.error("刷新明细列表失败:", error);
        uni.showToast({
          title: "刷新数据失败",
          icon: "none",
        });
      }
    },

    async updateDetailLocationStatus(item, executeArea, remainingQty) {
      // 构建更新参数，与Web端完全保持一致
      const actualQty = parseFloat(executeArea.executeQuantity || 0);

      const updateParams = {
        id: item.id,
        planWarehouseId: executeArea.executeWarehouseId,
        planLocationId: executeArea.executeLocationId,
        actualQuantity: actualQty,
        // 设置实际入库仓库和库位与计划相同，与Web端逻辑一致
        actualWarehouseId: executeArea.executeWarehouseId,
        actualLocationId: executeArea.executeLocationId,
        updateInventory: false, // 始终设置为false，表示仅更新明细，不更新库存
      };

      // 计算入库状态
      const planQty = parseFloat(item.planQuantity || 0);

      // 如果是全部入库状态，添加额外参数
      if (remainingQty <= 0) {
        updateParams.inboundStatus = "1"; // 设置为已入库状态(1)
        updateParams.inboundOrderId = this.inboundOrderId;
        updateParams.materialCode = item.materialCode;
      }

      // 当实际数量不等于0且库位状态不等于5时，设置库位状态为"占用(2)"
      // 但在库位已满的情况下，设置库位状态为"已满(5)"
      if (actualQty > 0) {
        updateParams.updateLocationStatus = true;
        updateParams.locationStatus = "5"; // 设置为"已满(5)"
        updateParams.updateInventory = false; // 确保不更新库存
      }

      try {
        const response = await this.$http.post(
          "/wms/inboundOrder/updateDetail",
          updateParams
        );

        if (!response.data || !response.data.success) {
          throw new Error(response.data?.message || "更新明细状态失败");
        }

        // 更新原明细的实际入库数量，确保显示正确的实际入库数量
        if (actualQty > 0) {
          item.actualQuantity = actualQty;
        }
      } catch (error) {
        console.error("更新明细状态失败:", error);
        throw error;
      }
    },

    async createNewDetailForRemaining(originalItem, remainingQty) {
      // 创建新明细的参数，与Web端逻辑保持一致
      const newDetailParams = {
        inboundOrderId: this.inboundOrderId,
        materialId: originalItem.materialId,
        materialCode: originalItem.materialCode,
        materialName: originalItem.materialName,
        materialType: originalItem.materialType,
        specification: originalItem.specification,
        unit: originalItem.unit,
        unitCost: originalItem.unitCost,
        // 设置计划数量为剩余未入库数量
        planQuantity: remainingQty,
        // 清除实际入库数据
        actualQuantity: 0,
        // 保留原仓库信息，清空库位信息
        planWarehouseId: originalItem.planWarehouseId,
        planWarehouseName: originalItem.planWarehouseName,
        planLocationId: null,
        planLocationName: "",
        // 设置状态信息
        inboundStatus: "0", // 未入库状态
        locationStatus: null,
        originalDetailId: originalItem.id, // 原始明细ID
      };

      try {
        // 调用后端接口创建新明细
        const response = await this.$http.post(
          "/wms/inboundOrder/addExtraLocationDetail",
          newDetailParams
        );

        if (response.data && response.data.success) {
          // 重新加载明细数据以显示新创建的明细
          await this.loadOrderDetails();
        } else {
          throw new Error(response.data?.message || "创建新明细失败");
        }
      } catch (error) {
        console.error("创建新明细失败:", error);
        throw error;
      }
    },

    // 获取状态颜色指示器
    getStatusColorIndicator(status) {
      const indicators = {
        1: "", // 空闲 - 绿色圆点
        2: "", // 占用 - 橙色圆点
        3: "", // 锁定 - 红色圆点
        4: "", // 禁用 - 黑色圆点
        5: "", // 已满 - 红色圆点
      };
      return indicators[status] || "";
    },

    // 更新库位状态
    updateLocationStatus(warehouseId, locationId, newStatus) {
      const locations = this.locationList[warehouseId] || [];
      const locationIndex = locations.findIndex((loc) => loc.id === locationId);
      if (locationIndex >= 0) {
        this.$set(locations, locationIndex, {
          ...locations[locationIndex],
          status: newStatus,
        });
        // 更新缓存的库位列表
        this.$set(this.locationList, warehouseId, [...locations]);
      }
    },

    // 计算实际入库数量：当actualQuantity不为0时使用actualQuantity，否则计算执行区域总和
    getActualQuantity(item) {
      // 当明细的实际入库数量不为0时，代表该明细已经执行过，则入库数量等于实际入库数量
      if (
        item.actualQuantity !== undefined &&
        item.actualQuantity !== null &&
        parseFloat(item.actualQuantity) > 0
      ) {
        return parseFloat(item.actualQuantity);
      }

      // 当实际入库数量=0时，计算执行区域的数量总和（用户正在执行入库）
      if (!item.executeAreas || item.executeAreas.length === 0) {
        return 0;
      }

      let totalQuantity = 0;
      item.executeAreas.forEach((area) => {
        if (area.executeQuantity && parseFloat(area.executeQuantity) > 0) {
          totalQuantity += parseFloat(area.executeQuantity);
        }
      });

      return totalQuantity;
    },

    getBusinessTypeText(businessType) {
      const typeMap = {
        11: "采购入库",
        12: "余料入库",
        13: "仓库调拨入库",
        19: "其他入库",
      };
      return typeMap[businessType] || "未知类型";
    },
  },
};
</script>

<style lang="scss" scoped>
.inbound-execute {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

// 自定义导航栏
.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height);
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
}

.nav-left {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.nav-left .cuIcon-back {
  font-size: 36rpx;
  color: #ffffff;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
}

.nav-right {
  width: 80rpx;
}

// 页面内容
.page-content {
  padding-top: calc(var(--status-bar-height) + 88rpx + 32rpx);
  padding-left: 32rpx;
  padding-right: 32rpx;
}

// 信息卡片
.info-card {
  background: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 2rpx solid #f0f2f5;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background: #fff7ed;
  color: #ea580c;
}

.status-completed {
  background: #f0fdf4;
  color: #16a34a;
}

.status-partial {
  background: #eff6ff;
  color: #2563eb;
}

.status-rejected {
  background: #fef2f2;
  color: #dc2626;
}

.detail-count {
  font-size: 28rpx;
  color: #6b7280;
}

.card-content {
  padding: 0 32rpx 32rpx;
}

// 信息行
.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 200rpx;
  font-size: 28rpx;
  color: #6b7280;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #1f2937;
  font-weight: 500;
}

// 明细列表
.detail-list {
  padding: 0 32rpx 32rpx;
}

.detail-item {
  background: #f8fafc;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  border: 2rpx solid #e2e8f0;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.material-code {
  font-size: 30rpx;
  font-weight: 600;
  color: #1e40af;
}

.material-status {
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.detail-pending {
  background: #fff7ed;
  color: #ea580c;
}

.detail-completed {
  background: #f0fdf4;
  color: #16a34a;
}

.detail-partial {
  background: #eff6ff;
  color: #2563eb;
}

.detail-content {
  margin-bottom: 20rpx;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  width: 180rpx;
  font-size: 26rpx;
  color: #6b7280;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  font-size: 26rpx;
  color: #374151;
}

.detail-value.quantity {
  font-weight: 600;
  color: #1f2937;
}

.detail-value.actual {
  color: #059669;
}

// 执行操作区域
.execute-section {
  background: #ffffff;
  border-radius: 8rpx;
  padding: 20rpx;
  border: 2rpx solid #e5e7eb;
}

.input-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.input-row:last-child {
  margin-bottom: 0;
}

.input-label {
  width: 140rpx;
  font-size: 26rpx;
  color: #374151;
  flex-shrink: 0;
}

.quantity-input,
.position-input {
  height: 60rpx;
  padding: 0 16rpx;
  border: 2rpx solid #d1d5db;
  border-radius: 6rpx;
  font-size: 26rpx;
  background: #ffffff;
  text-align: right;
  width: 150rpx;
  flex-shrink: 0;
}

.unit-text {
  margin-left: 12rpx;
  font-size: 24rpx;
  color: #6b7280;
  width: 40rpx;
  flex-shrink: 0;
}

.picker-input {
  flex: 1;
  height: 60rpx;
  padding: 0 16rpx;
  border: 2rpx solid #d1d5db;
  border-radius: 6rpx;
  font-size: 26rpx;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker-text {
  flex: 1;
  text-align: right;
  color: #374151;
}

.picker-icon {
  color: #999;
  font-size: 24rpx;
}

.location-full-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #ff9500 0%, #ff6b35 100%);
  border-radius: 12rpx;
  margin-top: 16rpx;
}

.location-full-btn .cuIcon-add {
  color: white;
  font-size: 28rpx;
  margin-right: 8rpx;
}

.location-full-btn text {
  color: white;
  font-size: 26rpx;
  font-weight: 600;
}

/* 库位状态颜色样式 */
.location-status-idle {
  color: #22c55e !important; /* 空闲 - 绿色 */
  font-weight: 600;
}

.location-status-occupied {
  color: #f59e0b !important; /* 占用 - 橙色 */
  font-weight: 600;
}

.location-status-locked {
  color: #ef4444 !important; /* 锁定 - 红色 */
  font-weight: 600;
}

.location-status-disabled {
  color: #6b7280 !important; /* 禁用 - 灰色 */
  font-weight: 600;
}

.location-status-full {
  color: #dc2626 !important; /* 已满 - 深红色 */
  font-weight: 600;
}

/* 库位状态显示样式 */
.status-display {
  width: 150rpx;
  height: 60rpx;
  padding: 0 16rpx;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-shrink: 0;
}

.status-text {
  font-size: 26rpx;
  font-weight: 600;
}

.location-full-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.execute-header {
  padding: 12rpx 0;
  margin-bottom: 16rpx;
  border-bottom: 1rpx solid #e5e7eb;
}

.execute-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #667eea;
}

// 底部操作按钮
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 24rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 600;
}

.action-btn.cancel {
  background: #f3f4f6;
  color: #6b7280;
  border: 2rpx solid #e5e7eb;
}

.action-btn.confirm {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
}

// 加载状态
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 48rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cuIcon-loading2 {
  font-size: 48rpx;
  color: #667eea;
  margin-bottom: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #6b7280;
}
</style>
